import React, { Component } from "react";
// 引入无状态组件
import TodoListUI from "./TodoListUI";

// 引入 store
import store from "./store";
import {
  changeInputValueAction,
  addTaskAction,
  removeTaskAction,
} from "./store/actionCreators";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    // 修改this指向
    this.changeInputValue = this.changeInputValue.bind(this);
    this.addTask = this.addTask.bind(this);
    this.removeTask = this.removeTask.bind(this);
    this.storeChange = this.storeChange.bind(this);
    // 订阅
    store.subscribe(this.storeChange);
  }
  render() {
    return (
      <TodoListUI
        inputValue={this.state.inputValue}
        list={this.state.list}
        changeInputValue={this.changeInputValue}
        addTask={this.addTask}
        removeTask={this.removeTask}
      />
    );
  }
  // 使得组件跟着更新
  storeChange() {
    this.setState(store.getState());
  }
  // 改变 input 的值
  changeInputValue(e) {
    const action = changeInputValueAction(e.target.value);
    store.dispatch(action);
  }
  // 添加任务
  addTask() {
    const action = addTaskAction();
    store.dispatch(action);
  }
  // 删除任务
  removeTask(index) {
    const action = removeTaskAction(index);
    store.dispatch(action);
  }
}

export default TodoList;
